<template>
  <div class="mine-box">
    <van-nav-bar
      title="我的钱包"
      left-text=""
      left-arrow
      @click-left="onClickLeft"
      class="nav-bar"
    />
    <div class="mywallet-container">
      <div class="wallet-top" >
        <div class="mawal_title">USDT</div>
        <van-row>
          <van-col span="21" class="container-top">
            <div class="num_value">{{ myWalObjUsdt.total_qyt }}&nbsp</div>
          </van-col>
          <van-col span="3" class="container-top">
            <img style="width:38px;" src="../../../../static/img/dollar.png" />
          </van-col>
        </van-row>
        <van-row class="mywallet-con-address" >
          <van-col span="8" class="mywal-btn">
            <span  @click="Recharge(2)" >充值</span>
          </van-col>
          <van-col span="8" class="mywal-btn">
            <span class="sweep" @click="openCamera('USDT')">扫一扫</span>
            <div class="picupload" @click="changeStatus('USDT')" style="display:none">
              <van-uploader :after-read="onRead" result-type="text" accept="image/*" multiple>
              </van-uploader>
            </div>
            <!-- <input type="file" v-if="isAndroid" id="file" class="get-camera" @change="getImage" accept="image/*"> -->
          </van-col>
          <van-col span="8" class="mywal-btn">
            <span @click="trade(2)" >提币</span>
          </van-col>
        </van-row>
      </div>
      <div class="wallet-top" >
        <div class="mawal_title">OBT</div>
        <van-row >
          <van-col span="24" >
            <van-col span="21" class="container-top">
              <div class="num_value">{{myWalObj.total_qyt}}&nbsp</div>
            </van-col>
            <van-col span="3" class="container-top">
              <img style="width:38px;" src="../../../../static/img/obtlogo.png" />
            </van-col>
          </van-col>
        </van-row>
        <van-row class="mywallet-con-address" >
          <van-col span="8" class="mywal-btn">
            <span @click="Recharge(0)" >兑换</span>
          </van-col>
          <van-col span="8" class="mywal-btn">
            <span @click="openCamera('OBT')">扫一扫</span>
            <div class="picupload" @click="changeStatus('OBT')" style="display:none">
              <van-uploader :after-read="onRead" result-type="text" accept="image/*" multiple>
              </van-uploader>
            </div>
            <!-- <input type="file" v-if="isAndroid" id="file" class="get-camera" @change="getImage" accept="image/*"> -->
          </van-col>
          <van-col span="8" class="mywal-btn">
            <span @click="qrcode">收款码</span>
          </van-col>
        </van-row>
      </div>
      <div class="mywallet-con">
        <div class="mywallet-con-record">交易记录</div>
      </div>
      <div class="wallet-top">
        <van-row
          class="mywallet-con-address"
          style="border-radius: 0;"
        >
          <van-col span="4">币种</van-col>
          <van-col span="6">时间</van-col>
          <van-col span="4">值</van-col>
          <van-col span="5">类型</van-col>
          <van-col span="5">转入来源</van-col>
        </van-row>
        <van-list
          v-model="loading"
          :finished="finished"
          @load="onLoad"
          :immediate-check="false"
          :offset="100"
          class="container"
        >
          <van-row
            class="mywallet-con-address"
            style="border-radius: 0;"
            v-for="(item, index) in HistoricalList"
            :key="index"
          >
            <van-col span="4">{{item.tk_code}}</van-col>
            <van-col span="6">{{item.created_on}}</van-col>
            <van-col span="4">{{item.qty}}</van-col>
            <van-col span="5">{{item.type}}</van-col>
            <van-col span="5">{{item.from_user.ref_code}}</van-col>
          </van-row>
        </van-list>
      </div>
    </div>

    <van-dialog
      v-model="showQrCode"
    >
      <div id="qrcode"></div>
    </van-dialog>
  </div>
</template>

<script>
  import QRCode from 'qrcodejs2'
  import { Toast } from 'vant';
  import { Dialog } from 'vant';
  export default {
    data(){
      return {
        showQrCode: false,
      	money:'',
        showChangeName: false,
        showChangePhone:false,
        showImgChoose: false,
        HistoricalList: [],
        myCroppa: {},
        config: {
            value: 'https://www.baidu.com',
            imagePath: './examples/assets/logo.png',
            filter: 'color'
        },
        erweimaControl:true,
        islogin:false,
        downloadButton: false,
        //  用户账l号信息
        accountList: [],

        //用户号码
        hideNum:null,

        //  绑定微信授权flag
        bindIndex: false,

        bindTitle:'待绑定',
        // 用户头像
        userAvatar:'',
        //  版本参数
        param_uuid:null,

        param_scource:null,

        usermobile:"",
        imgsrc:"",
        userid:"",
          myWalObj:{},
          myWalObjUsdt:{},
          lastPageUrl:"",
        loading: false,
        finished: false,
        pageCount: 10,
        pageIndex: 0,
        isIos: true,
        isAndroid: true,
        file: [],
        jumpStatus: null,
        nickName: ''
      }
    },
    created(){

    },
    mounted(){
      if(this.andOrIos()) { //android
        this.isIos = false;
        this.isAndroid = true;
      }else{
        this.isIos = true;
        this.isAndroid = false;
      }
      let userMessage = JSON.parse(sessionStorage.getItem("usermessage"));
      this.userid = userMessage.user.ref_code;
      this.nickName = userMessage.user.nick_name;

      this.lastPageUrl = sessionStorage.getItem("lastAndNowPage").split('-')[1];
    sessionStorage.setItem("lastAndNowPage",this.lastPageUrl+"-/mywallet");
      if(!sessionStorage.getItem("usermessage")) {
        this.$router.push('/login');
      }
        token_g = JSON.parse(sessionStorage.getItem("usermessage")).token;
      this.getMyWal();
      this.getMyRecord();
    },
    methods:{
      openCamera(status){
        let $this = this
        try{
          var FNScanner = api.require('FNScanner');
          FNScanner.openScanner({autorotation: true}, function(ret, err){
            if (ret) {
              if(ret.eventType == 'success'){
                // location.href = ret.content;

                $this.$router.push({
                  path: ret.content + `&status=${status}`,
                });
              }
            } else {
              alert(JSON.stringify(err));
            }
          });
        }catch(e){
          this.$router.push({
            path: `/carry`
          });
        }
      },
      onClickLeft() {
        this.$router.push('/wallet')
      },
    	Recharge(cont){
    		if(cont == 2){
    			this.$router.push({
		    		path:'/Recharge',
		    		query: {
		        	address:this.myWalObjUsdt.address
		       	}
		    	})
    		}else{
    			this.$router.push({
		    		path:'/OBTRecharge',
		    		query: {
		        	address:this.myWalObjUsdt.address
		       	}
		    	})
    		}
    	},
    	transferAccounts(){
    		this.$router.push({
    			path:'/carry'
    		});
    	},
    	trade(){
    		this.$router.push('/Putforward');
    	},
	    getMyWal() {
        if(!token_g) {
            Dialog.alert({
                message: '请先登录'
            }).then(() => {
                // on close
            });
            return false
        } else {
            // 头部信息
	        this.$axios({
	            method: 'GET',
	            url: url_g + '/asset/',
	            headers: {
	                'Authorization': 'Bearer ' + token_g
	            }
	        }).then((res) => {
	            // console.log(res)
	            for(var i=0;i<res.data.results.length;i++ ){
	            	res.data.results[i].total_qyt = Math.floor(res.data.results[i].total_qyt * 100) / 100
	            }
	            if(res.data) {
	                this.myWalObj = res.data.results[0]
	                this.myWalObjUsdt = res.data.results[1]
	            }
	        }).catch((e) => {
              Toast(e.response.data.detail);
	        });
        }
	    },
      onLoad() {
        this.pageIndex ++
        this.getMyRecord()
      },
	    getMyRecord() {
        let params = {type: 0}
        if(this.pageIndex != 0) {
          params.page = this.pageIndex + 1
        }
        this.$axios({
          method: 'GET',
          url: url_g + '/transaction/',
          params: params,
          headers: {
            'Authorization': 'Bearer ' + token_g
          }
        }).then((res) => {
          console.log(res)
          if(res.data && res.data.results){
            res.data.results.map(function(item,index){
              item.created_on = item.created_on.replace('T'," ")
              if(item.type == "1"){
                item.type = "买入"
              }else if(item.type == "2"){
                item.type = "卖出"
              }else if(item.type == "3"){
                item.type = "买入矿池"
              }else if(item.type == "4"){
                item.type = "挖矿"
              }else if(item.type == "5"){
                item.type = "节点奖励"
              }else if(item.type == "6"){
                item.type = "直推奖"
              }else if(item.type == "7"){
                item.type = "新用户红包奖励"
              }else if(item.type == "8"){
                item.type = "转入"
              }else if(item.type == "9"){
                item.type = "转出"
              }else if(item.type == "A"){
                item.type = "抽奖"
              }
            })

            // list
            let newArr = res.data.results
            this.pageCount = res.data.count
            for (let i = 0; i < newArr.length; i ++) {
              var num = ''
              num =  newArr[i].qty;
              num = Math.floor(num * 100) / 100
              newArr[i].qty = num

              this.HistoricalList.push(newArr[i])
            }

            this.loading = false;
            if (this.HistoricalList.length >= this.pageCount) {
              this.finished = true;
            }
          }
        }).catch((e) => {
              Toast(e.response.data.detail);
        });
	    },
      qrcode() {
        let $this = this;

        this.$router.push({
          path:'/Recharge',
          query: {
            address: `/carry?id=${$this.userid}&nickName=${$this.nickName}`,
            title: '收款码'
          }
        })

        // if(this.erweimaControl){
        //   let qrcode = new QRCode('qrcode', {
        //     width: 200,
        //     margin:"0 auto",
        //     height: 200, // 高度
        //     text: `${$this.userid}|${$this.nickName}`, // 二维码内容
        //     render: 'table', // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
        //     background: '#f0f'
        //     // foreground: '#ff0'
        //   })
        //   this.erweimaControl = false;
        //   setTimeout(function(){
        //     let ele = document.getElementById("qrcode");
        //     $this.imgsrc = ele.children[1].getAttribute("src");
        //     $this.showQrCode = true;
        //   },1000)
        // } else {
        //   $this.showQrCode = true;
        // }
      },
      onRead(file) {
        let $this = this;
        if(file.length > 1){
          file.map(function(item,index){
            $this.file.push(item.file);
          })
        }else{
          $this.file.push(file.file);
        }
        let formData = new FormData();
        formData.append('img_file', $this.file[0]);
        $this.loadingControl = true;
        $this.$axios.post(url_g + "/qrdecode/",formData
        ).then((res)=>{
          console.log(res)
          $this.file = [];
          $this.loadingControl = false;
          if(res && res.data && res.data.content){
            let urlData = res.data.content.split('|')
            let id = urlData[0], nickName = urlData[1]

            this.$router.push({
              path:'/carry',
              query: {
                id: id,
                nickName: nickName,
                status: this.jumpStatus
              }
            });
          }else{
            Toast('请选择邀请的二维码图片');
          }
        }).catch((e)=>{
          $this.loadingControl = false;
          $this.file = [];
          Toast(e.response.data.detail);
        })
      },
      getImage() {
        var $this = this;
        let fileInput = document.getElementById('file')
        for(let i = 0; i < fileInput.files.length;i++){
          this.file.push(fileInput.files[i])
        }
        let formData = new FormData();
        formData.append('img_file', $this.file[0]);
        $this.loadingControl = true;
        $this.$axios.post(url_g + "/qrdecode/",formData
        ).then((res)=>{
          $this.file = [];
          $this.loadingControl = false;
          if(res && res.data && res.data.content && res.data.content.indexOf('http') != -1){
            window.open(res.data.content)
          }else{
            this.toast =  Toast('请选择邀请的二维码图片');
          }
        }).catch((e)=>{
          $this.loadingControl = false;
          $this.file = [];
            Toast(e.response.data.detail);
        })
      },
      changeStatus(e) {
        this.jumpStatus = e
      },
      andOrIos() {
        let u = navigator.userAgent;
        let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        return isAndroid
      },
    }
  }
</script>

<style scoped>
.mine-box{
  height: 100vh;
  width: 100%;
  overflow: auto;
  background: -webkit-linear-gradient( top,#028aed,#273eec);
  color: #fff;
}
.van-cell-group {
  background-color: transparent;
}
.nav-bar {
  color: #000;
}
.mywallet-container {
  width: calc(100% - 20px);
  padding: 0 10px;
}
.mawal_title{
	color: #fff;
	text-align: left;
	padding-left:7px ;
}
.mawal_title span{
	font-size: 12px;
}
.num_value{
	font-size: 16px;
  padding-left:7px;
}
.mywal-btn{
  position: relative;
  background: transparent;
}
.mywal-btn span{
	display: block;
}
.wallet-top{
	border:1px solid #CCCCCC;
  border-radius:5px;
  margin-top: 10px;
  margin-bottom: 10px;
  text-align: left;
  height: auto;
  line-height: 36px;
  border-bottom: 1px solid #ccc;
  font-size: 14px;
  justify-content: center;
}
.wallet-top-luck{
  width: 80px;
  height: 26px;
  border-radius: 13px;
  line-height: 26px;
  border: 1px solid #ccc;
  margin: 10px auto auto;
}
.mywallet-con{

}
.mywallet-con-address{
	border-radius: 10px;
  text-align: center;
  border-bottom: 1px solid #CCCCCC;
}
.mywallet-con-address:last-child{
  border-bottom:none !important;
}
.mywallet-con-record{
  margin: 20px 0 10px 10px;
  font-size: 18px;
  font-weight: bold;
}
.picupload {
  position: absolute;
  top: 0;
  height: 36px;
  width: 100%;
}
.get-camera {
  position: absolute;
  top: 0;
  height: 36px;
  width: 100%;
  opacity:0;
}
#qrcode {
  width: 200px;
  height: auto;
  margin: 10px auto;
  margin-top: 40px;
}
</style>
